The break keyword in C is used within loops (for, while, do-while) and switch statements. It allows the program to prematurely exit the loop or switch block and continue with the next statement after the loop or switch.
In loops: When encountered, the break statement terminates the loop immediately, and the control moves to the statement following the loop.
In switch statements: The break statement is used to exit the switch block after a case is executed. Without break, the program will fall through to the next case, executing code for subsequent cases until a break statement is encountered or the switch block ends.
#include <stdio.h>
int main() {
int i;
// Using break in a for loop
printf("Using break in a for loop:\n");
for (i = 1; i <= 5; i++) {
printf("%d ", i);
if (i == 3) {
break; // When i is 3, break the loop
}
}
printf("\n");
// Using break in a while loop
printf("\nUsing break in a while loop:\n");
i = 1;
while (i <= 5) {
printf("%d ", i);
if (i == 3) {
break; // When i is 3, break the loop
}
i++;
}
printf("\n");
// Using break in a do-while loop
printf("\nUsing break in a do-while loop:\n");
i = 1;
do {
printf("%d ", i);
if (i == 3) {
break; // When i is 3, break the loop
}
i++;
} while (i <= 5);
printf("\n");
// Using break in a switch statement
printf("\nUsing break in a switch statement:\n");
int option = 2;
switch (option) {
case 1:
printf("Option 1 selected\n");
break;
case 2:
printf("Option 2 selected\n");
break; // Break after executing case 2
case 3:
printf("Option 3 selected\n");
break;
default:
printf("Invalid option\n");
}
return 0;
}
Using break in a for loop:
1 2 3
Using break in a while loop:
1 2 3
Using break in a do-while loop:
1 2 3
Option 2 selected
In the first three loops, the loop stops when i becomes equal to 3 because of the break statement. This is why the output is 1 2 3.
In the switch statement, when option is equal to 2, it executes the corresponding case and then encounters break, which causes the switch block to terminate. Hence, the output is Option 2 selected.
What is the purpose of the 'break' statement in C?
In which control structures is the 'break' statement commonly used?
What happens when 'break' is executed within a switch statement in C?